<template>
  <div class="tools_box">
    <el-dialog :close-on-click-modal='false' v-drag top="10vh" :title="$t('编辑')" v-if="visible" :visible.sync="visible" :showClose="false" width="700px" @close="backParent">
      <el-form :model="form" :rules="rules" :hide-required-asterisk="true" label-position="left" style="margin:0 20px;" ref="form">
        <el-form-item :label="$t('地址组名称')" :label-width="formLabelWidth" prop="name">
          <el-input v-emoji size='small' v-model="form.name" autocomplete="off" ref="name"></el-input>
        </el-form-item>
        <el-form-item :label="$t('描述')" :label-width="formLabelWidth" prop="desc">
          <el-input v-emoji size='small' type="textarea" ref="desc" @keydown.native="handleKeyCode($event)" :placeholder="$t('请输入内容')" :autosize="{ minRows: 2, maxRows: 4}" v-model="form.desc">
          </el-input>
        </el-form-item>

        <!--    添加对象页面-->
        <div>
          <el-button type="success" @click="add_addr" size="small" class="addAddr" style="margin-bottom:10px;">{{$t('添加对象')}}</el-button>
          <el-dialog :close-on-click-modal='false' top="5vh" v-drag :title="$t('添加对象')" v-if="dialogAddrFormVisible" :visible.sync="dialogAddrFormVisible" width="800px" append-to-body>
            <el-table size='mini' :data="addr_list_info" tooltip-effect="dark" header-align="center" max-height="500px" align="center" style="width: 100%" @selection-change="handleSelectionChange">
              <el-table-column align="center" type="selection" width="55">
              </el-table-column>
              <el-table-column align="center" prop="name" :label="$t('名称')">
                <template slot-scope="scope">
                  <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name">
                  </tooltip>
                </template>
              </el-table-column>
              <el-table-column align="center" prop="ip_type" :label="$t('类型')" :formatter="ipTypeName">
              </el-table-column>
              <el-table-column align="center" prop="ip" label="IP/MAC">
                <template slot-scope="scope">
                  <tooltip :html="classMapShow(scope.row,';<br/>')" :content="classMapShow(scope.row,',')" class="wid190" :refName="scope.row.name"></tooltip>
                </template>
              </el-table-column>
            </el-table>
            <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="add_addr_submit" class="innerAddSubmit">{{$t('确 定')}}</el-button>
              <el-button @click="dialogAddrFormVisible = false" class="innerAddClose">{{$t('取 消')}}</el-button>
            </div>
          </el-dialog>

          <el-table size='mini' :data="form.member" border style="width: 100%" max-height="400px">
            <el-table-column align="center" prop='name' :label="$t('名称')">
              <template slot-scope="scope">
                <tooltip :html="scope.row.name" :content="scope.row.name" class="wid190" :refName="scope.row.name">
                </tooltip>
              </template>
            </el-table-column>
            <el-table-column align="center" fixed="right" :label="$t('操作')" width="120">
              <template slot-scope="scope">
                <el-button @click.native.prevent="deleteRow(scope.$index, form.member)" :class="'del' + scope.$index" type="danger" plain size="mini">
                  {{$t('删除')}}
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="sendCommand(form)" class="addSubmit">{{$t('确 定')}}</el-button>
        <el-button @click="backParent" class="addClose">{{$t('取 消')}}</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import { editAddrGroup } from '@/api/list/addr-group'
import { getAddrArray } from '@/api/list/addr'
import { inputClass, texttextClass } from '@/utils/input-class.js'
export default {
  props: [
    'addr_info',
    'editVisible',
    'tableData'
  ],
  name: 'AddrGroupEdit',
  data () {
    var validateName = (rule, value, callback) => {
      if (!String(value).trim()) {
        callback(new Error(this.$t('请输入对象名称')))
      } else {
        callback()
      }
    }
    const validateDescribe = (rule, value, callback) => {
      if (value.length > 255) {
        callback(new Error(this.$t('描述长度不能超过255字节')))
      } else {
        callback()
      }
    }
    return {
      old_name: {},
      old_desc: '',
      form: {
        member: []
      },
      addr_list_info: [],
      addrSelection: [],
      rules: {
        name: [{ required: false, validator: validateName, trigger: 'blur' }],
        desc: [{ required: false, trigger: 'blur', validator: validateDescribe }]
      },
      formLabelWidth: '15%',
      visible: false,
      dialogAddrFormVisible: false
    }
  },
  watch: {
    addr_info: {
      handler (val, oldVal) {
        if (oldVal) {
          this.form = val
          let new_array = []
          this.form.member.forEach((item, index, array) => {
            new_array.push({ 'name': item })
          })
          this.form.member = new_array
          this.form.old_name = val.name
          this.old_desc = val.desc
        }
      },
      immediate: true
    },
    'dialogAddrFormVisible': {
      handler (newVal) {
        if (newVal === true) {
          this.addrSelection = []
          this.addr_list_info = []
          getAddrArray().then(response => {
            this.addr_list_info = response.info
            this.addr_list_info.forEach((item, index, array) => {
              if (item.sys === 1) {
                delete this.addr_list_info[index]
              }
            })
          })
        }
      },
      immediate: true
    },
    editVisible: {
      handler (val, oldVal) {
        this.visible = val
        if (val === true) {
          this.$nextTick(() => {
            const data = ['name']
            const textdata = ['desc']
            inputClass(this.$refs, data)
            texttextClass(this.$refs, textdata)
          })
        }
      },
      immediate: true
    },
    'form.desc': {
      handler (newVal) {
        if (newVal) {
          this.form.desc = newVal.replace(/[\r\n]/g, '')
        }
      },
      immediate: true
    }
  },
  methods: {
    handleSelectionChange (val) {
      this.addrSelection = val
    },
    sendCommand (form) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if (form.member && form.member.length > 0) {
            let formData = JSON.parse(JSON.stringify(form))
            let member = []
            for (let item of form.member) {
              member.push(item.name)
            }
            formData.member = member.join(',')
            editAddrGroup(formData).then(response => {
              if (response.status === 0) {
                this.$messages.success(this.$t('编辑成功'))
              }
              this.dialogFormVisible = false
              this.$emit('quxiao', false)
              this.$emit('listData')
            })
          } else {
            this.$messages.error(this.$t('对象不能为空'))
          }
        }
      })
    },
    add_addr_submit () {
      this.addrSelection.forEach(values => {
        if (this.addr_info.member.findIndex(item => item.name === values.name) === -1) {
          this.addr_info.member.push({ 'name': values.name })
        }
      })
      this.dialogAddrFormVisible = false
    },
    ipTypeName (row) {
      switch (row.ip_type) {
        case 1:
          return 'IPv4'
        case 2:
          return 'IPv4-NET'
        case 3:
          return 'IPv4-RANGE'
        case 4:
          return 'IPv6'
        case 5:
          return 'IPv6-NET'
        case 7:
          return 'MAC'
        default:
          return this.$t('其他')
      }
    },
    updateView (e) {
      this.$forceUpdate()
    },
    add_addr () {
      this.dialogAddrFormVisible = true
    },
    backParent () {
      this.$emit('quxiao', false)
    },
    deleteRow (index, rows) {
      rows.splice(index, 1)
    },
    classMapShow (data, str) {
      if (data.ip_type === 7) {
        return data.mac
      } else {
        let reStr = ''
        data.ip.forEach((val, index) => {
          if (index < 1 && str === ',') {
            reStr += val
          } else if (str === ',') {
            reStr += str + val
          } else {
            reStr += val + str
          }
        })
        return reStr
      }
    },
    handleKeyCode (event) {
      if (event.keyCode === 13) {
        event.preventDefault() // 阻止浏览器默认换行操作
        return false
      }
    }
  }
}
</script>

<style scoped>
.tools_box {
  text-align: left;
}
.circle {
  padding: 5px;
}
</style>
